package com.example.warehouse.sys.service.impl;

import com.example.warehouse.sys.dao.persist.respository.IPermissionRepository;
import com.example.warehouse.sys.pojo.vo.PermissionListItemVO;
import com.example.warehouse.sys.pojo.vo.PermissionTreeItemVO;
import com.example.warehouse.sys.service.IPermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Slf4j
public class PermissionServiceImpl implements IPermissionService {
    public PermissionServiceImpl() {
        log.info("");
    }

    @Autowired
    private IPermissionRepository permissionRepository;

    @Override
    public List<PermissionTreeItemVO> listTree() {
        log.debug("开始处理【获取类别树】的业务，参数：无");
        List<PermissionTreeItemVO> permissionTreeItemVOS = new ArrayList<>();

        List<PermissionListItemVO> permissionListItemVOS = permissionRepository.list();
        Map<Long, PermissionListItemVO> allCategoryMap = transformListToMap(permissionListItemVOS);
        for (Long key : allCategoryMap.keySet()) {
            PermissionListItemVO mapItem = allCategoryMap.get(key);
            if (mapItem.getPid() == 0) {
                PermissionTreeItemVO permissionTree = convertListItemToTreeItem(mapItem);
                permissionTreeItemVOS.add(permissionTree);
                fillChildren(mapItem, permissionTree, allCategoryMap);
            }
        }

        return permissionTreeItemVOS;
    }

    private Map<Long, PermissionListItemVO> transformListToMap(List<PermissionListItemVO> categoryList) {
        Map<Long, PermissionListItemVO> categoryMap = new LinkedHashMap<>();
        for (PermissionListItemVO categoryListItemVO : categoryList) {
            if (categoryListItemVO.getEnable() == 0) {
                continue;
            }
            categoryMap.put(categoryListItemVO.getId(), categoryListItemVO);
        }
        return categoryMap;
    }

    private void fillChildren(PermissionListItemVO listItem, PermissionTreeItemVO currentTreeItem, Map<Long, PermissionListItemVO> allPermissionMap) {

            currentTreeItem.setChildren(new ArrayList<>());
            Set<Long> keySet = allPermissionMap.keySet();
            for (Long key : keySet) {
                PermissionListItemVO mapItem = allPermissionMap.get(key);
                if (mapItem.getPid() == listItem.getId()) {
                    PermissionTreeItemVO permissionTreeItemVO = convertListItemToTreeItem(mapItem);
                    currentTreeItem.getChildren().add(permissionTreeItemVO);
                        fillChildren(mapItem, permissionTreeItemVO, allPermissionMap);
                }
            }

    }

    private PermissionTreeItemVO convertListItemToTreeItem(PermissionListItemVO listItem) {
        return new PermissionTreeItemVO()
                .setId(listItem.getId())
                .setLabel(listItem.getName());
    }
}
